class Solution {
public:
    vector<int> father;
    int sets;

    void build(int n)
    {
        for (int i = 0; i < n; i++)
        {
            father.push_back(i);
        }
        sets = n;
    }

    int find(int n)
    {
        if (n != father[n])
            father[n] = find(father[n]);
        return father[n];
    }

    void union_(int x, int y)
    {
        int fx = find(x), fy = find(y);
        if (fx != fy)
        {
            father[fx] = fy;
            sets--;
        }
    }

    int minSwapsCouples(vector<int>& row) {
        int rown = row.size();
        build(rown / 2);
        int res = 0;
        for (int i = 0; i < rown; i += 2)
            union_(row[i] / 2, row[i + 1] / 2);
        res = rown / 2 - sets;
        return res;
    }
};